package com.master.train.member.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.master.train.common.context.LoginMemberContext;
import com.master.train.common.utils.PageUtils;
import com.master.train.common.utils.R;
import com.master.train.member.entity.PassengerEntity;
import com.master.train.member.service.PassengerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;



/**
 * 乘车人
 *
 * @author master
 * @email 3221057417@qq.com
 * @date 2025-07-02 18:01:07
 */
@RestController
@RequestMapping("member/passenger")
public class PassengerController {
    @Autowired
    private PassengerService passengerService;

    /**
     * 列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("member:passenger:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = passengerService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("member:passenger:info")
    public R info(@PathVariable("id") Long id){
		PassengerEntity passenger = passengerService.getById(id);

        return R.ok().put("passenger", passenger);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
//    @RequiresPermissions("member:passenger:save")
    public R save(@RequestBody PassengerEntity passenger){

        QueryWrapper<PassengerEntity> wrapper = new QueryWrapper<PassengerEntity>();
        QueryWrapper<PassengerEntity> eq = wrapper.eq("id_card", passenger.getIdCard());
        long count = passengerService.count(eq);
        DateTime now = new DateTime();
        if (count>0){
            PassengerEntity one = passengerService.getOne(eq);
            one.setName(passenger.getName());
            one.setType(passenger.getType());
            one.setUpdateTime(now);
            passengerService.updateById(one);
        }else {
            Snowflake snowflake = new Snowflake(1, 1);
            passenger.setMemberId(LoginMemberContext.getId());
            passenger.setId(snowflake.nextId());
            passenger.setCreateTime(now);
            passenger.setUpdateTime(now);
            passengerService.save(passenger);

        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("member:passenger:update")
    public R update(@RequestBody PassengerEntity passenger){
		passengerService.updateById(passenger);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping ("/delete")
    public R delete(@RequestBody Long[] ids){
        passengerService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
